import { BattleArea, BattleAreaActionType, BattleAreaActionTypeMap, BattleAreaType, BattleAreaTypeMap, BattleAreaTypeOptions, BattleAreaTypeSwitchOptions, UaCard } from "../../../models/ua-card.model";
import { UaUserDeckDto } from "../../../models/ua-user-deck.model";
import { GlobalService } from "../../../services/global.service";
import { UserDeckService } from "../../../services/ua-user-deck.service";

// pages/user/deck-battle-test/deck-battle-test.page.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    FILE_HOST: GlobalService.FILE_HOST,
    // 玩家1的战场区域
    areasP1: {} as BattleArea,
    activeStatusP1: {} as { [key: string]: boolean },
    // 玩家2的战场区域
    areasP2: {} as BattleArea,
    activeStatusP2: {} as { [key: string]: boolean },
    // 手牌确认弹窗状态
    handConfirmModalVisible: false,
    BattleAreaType: BattleAreaType,
    BattleAreaTypeMap: BattleAreaTypeMap,
    changeHandOnceP1: false,
    changeHandOnceP2: false,
    // 当前活跃玩家 (1 或 2)
    activePlayer: 1,
    selectedPlayer: 0,
    // 战场区域布局配置
    BattleAreaLayout: {
      // 非活跃玩家第一行 (场外、能量线4-1、移除区)
      inactiveRow1: [
        BattleAreaType.OUTSIDE,
        BattleAreaType.E4,
        BattleAreaType.E3,
        BattleAreaType.E2,
        BattleAreaType.E1,
        BattleAreaType.REMOVE
      ],
      // 非活跃玩家第二行 (卡组、前线4-1、生命区)
      inactiveRow2: [
        BattleAreaType.DECK,
        BattleAreaType.F4,
        BattleAreaType.F3,
        BattleAreaType.F2,
        BattleAreaType.F1,
        BattleAreaType.LIFE
      ],
      // 活跃玩家第三行 (生命区、前线1-4、卡组)
      activeRow3: [
        BattleAreaType.LIFE,
        BattleAreaType.F1,
        BattleAreaType.F2,
        BattleAreaType.F3,
        BattleAreaType.F4,
        BattleAreaType.DECK
      ],
      // 活跃玩家第四行 (移除区、能量线1-4、场外)
      activeRow4: [
        BattleAreaType.REMOVE,
        BattleAreaType.E1,
        BattleAreaType.E2,
        BattleAreaType.E3,
        BattleAreaType.E4,
        BattleAreaType.OUTSIDE
      ],
      // 活跃玩家第五行 (展示区、操作区、手牌)
      activeRow5: [
        BattleAreaType.DISPLAY,
        BattleAreaType.OP,
        BattleAreaType.HAND
      ]
    },
    // 其他数据
    selectedType: '' as BattleAreaType,
    actionType: '' as BattleAreaActionType,
    selectedIndex: -1,
    detailVisible: false,
    detailCard: {} as UaCard,
    detailOverlayProps: {
      zIndex: 11500
    },
    BattleAreaTypeOptions: BattleAreaTypeOptions,
    BattleAreaTypeSwitchOptions: BattleAreaTypeSwitchOptions,
    BattleAreaActionType: BattleAreaActionType,
    BattleAreaActionTypeMap: BattleAreaActionTypeMap,
    BACK_IMG: GlobalService.FILE_HOST + '/jp/images/cardlist/card/img_card_jp.png',
    // 玩家信息
    player1Name: '玩家1',
    player2Name: '玩家2',
    // 手牌确认状态
    handConfirmedP1: false,
    handConfirmedP2: false,
    // 手牌替换状态
    handChangedP1: false,
    handChangedP2: false,
  },

  customData: {
    // 玩家1卡组
    deckCardListP1: [] as number[],
    // 玩家2卡组
    deckCardListP2: [] as number[],
    // 玩家1洗牌后的卡组
    shuffledP1: [] as number[],
    // 玩家2洗牌后的卡组
    shuffledP2: [] as number[],
    // 卡牌映射表
    cardMap: {} as { [key: number]: UaCard },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options: any) {
    wx.setNavigationBarTitle({
      title: '卡组对战测试'
    });

    // 使用Promise.all同时加载两个卡组
    const loadPromises = [];

    if (options.deckId1) {
      loadPromises.push(this.loadDeck(options.deckId1, 1));
    }
    if (options.deckId2) {
      loadPromises.push(this.loadDeck(options.deckId2, 2));
    } else if (options.deckId1) {
      // 如果只提供了一个卡组ID，则两个玩家使用相同的卡组
      loadPromises.push(this.loadDeck(options.deckId1, 2));
    }

    // 等待所有卡组加载完成
    await Promise.all(loadPromises);

    // 初始化战场状态
    this.initBattleStatus();
  },

  /**
   * 初始化战场状态
   */
  initBattleStatus() {
    // 初始化玩家1
    this.shuffleP1();

    // 初始化玩家2
    this.shuffleP2();

    // 重置游戏状态
    this.setData({
      activePlayer: 1,
      turnCount: 1,
      currentTurn: 1,
      handConfirmedP1: false,
      handConfirmedP2: false,
      handChangedP1: false,
      handChangedP2: false,
      selectedPlayer: 1
    });

    // 显示手牌确认弹窗
    this.setData({
      handConfirmModalVisible: true
    });
  },

  /**
   * 处理手牌确认
   */
  handleHandConfirm() {
    const { selectedPlayer } = this.data;

    if (selectedPlayer === 1) {
      this.confirmHandP1();
      // 切换到玩家2
      this.setData({
        selectedPlayer: 2
      });
    } else {
      this.confirmHandP2();
      // 关闭弹窗
      this.setData({
        handConfirmModalVisible: false,
        selectedType: '' as BattleAreaType,
        selectedIndex: -1,
        selectedPlayer: 0
      });
    }
  },

  /**
   * 处理手牌切换
   */
  handleHandChange() {
    const { selectedPlayer } = this.data;

    if (selectedPlayer === 1) {
      this.changeHandP1();
    } else {
      this.changeHandP2();
    }
  },

  /**
   * 加载卡组
   */
  loadDeck(deckId: string, playerNum: number) {
    UserDeckService.findById(deckId).then((response: UaUserDeckDto) => {
      if (response) {
        const cardMap: { [key: number]: UaCard } = { ...this.customData.cardMap };
        const cardList = response.cardDtoList ?? [];
        cardList.map((card: UaCard) => {
          card.cardImgSm = card.cardImg?.replace('.png', '.jpg');
          cardMap[card.id!] = card;
        });
        this.customData.cardMap = cardMap;

        const deckCardList = [];
        for (const item of response.cardList ?? []) {
          for (let i = 0; i < item.count; i++) {
            deckCardList.push(item.id);
          }
        }

        if (playerNum === 1) {
          this.customData.deckCardListP1 = deckCardList;
          this.setData({
            player1Name: response.name ? `${response.name}` : '玩家1'
          });
          this.shuffleP1();
        } else {
          this.customData.deckCardListP2 = deckCardList;
          this.setData({
            player2Name: response.name ? `${response.name}` : '玩家2'
          });
          this.shuffleP2();
        }
      }
    });
  },

  // 移除对战日志相关方法

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 通用洗牌方法
   */
  shuffleDeck(player: number) {
    const deckKey = player === 1 ? 'deckCardListP1' : 'deckCardListP2';
    const shuffledKey = player === 1 ? 'shuffledP1' : 'shuffledP2';
    const areasKey = player === 1 ? 'areasP1' : 'areasP2';

    const shuffled = [...this.customData[deckKey]];
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    this.customData[shuffledKey] = shuffled;

    // 初始化战场区域
    const areas: BattleArea = {};
    for (const area of Object.values(BattleAreaType)) {
      areas[area] = [];
    }

    // 将洗好的牌放入牌库
    areas[BattleAreaType.DECK] = shuffled.map(id => ({
      id,
      asFold: true,
      cardImgSm: this.customData.cardMap[id].cardImgSm
    }));

    this.setData({
      [areasKey]: areas
    });

    // 移除洗牌日志
  },

  /**
   * 玩家1洗牌并抽初始手牌
   */
  shuffleP1() {
    this.shuffleDeck(1);
    this.drawP1(7); // 初始抽7张牌
    this.setData({
      handConfirmedP1: false,
      handChangedP1: false
    });
  },

  /**
   * 玩家2洗牌并抽初始手牌
   */
  shuffleP2() {
    this.shuffleDeck(2);
    this.drawP2(7); // 初始抽7张牌
    this.setData({
      handConfirmedP2: false,
      handChangedP2: false
    });
  },

  draw() {
    this.drawCard(this.data.activePlayer, 1);
  },

  /**
   * 通用抽牌方法
   */
  drawCard(player: number, count: number = 1) {
    console.log('drawCard', player, count);
    const playerKey = player === 1 ? 'areasP1' : 'areasP2';
    const areas = { ...this.data[playerKey] };
    const deck = [...areas[BattleAreaType.DECK]];
    const hand = [...areas[BattleAreaType.HAND]];

    if (deck.length === 0) {
      return; // 牌库已空，无法抽牌
    }

    const actualCount = Math.min(count, deck.length);
    for (let i = 0; i < actualCount; i++) {
      const card = deck.shift();
      if (card) {
        card.asFold = false;
        hand.unshift(card);
      }
    }

    areas[BattleAreaType.DECK] = deck;
    areas[BattleAreaType.HAND] = hand;

    this.setData({
      [playerKey]: areas
    });

  },

  /**
   * 玩家1抽牌
   */
  drawP1(count: number = 1) {
    this.drawCard(1, count);
  },

  /**
   * 玩家2抽牌
   */
  drawP2(count: number = 1) {
    this.drawCard(2, count);
  },

  onDetailVisibleChange(e: any) {
    this.setData({
      detailVisible: e.detail.visible,
    });
  },

  /**
   * 隐藏卡牌详情
   */
  hideCardDetail() {
    this.setData({
      detailVisible: false
    });
  },

  /**
   * 选择卡牌
   */
  selectCard(e: any) {
    const { player, type, index } = e.currentTarget.dataset;
    const playerNum = parseInt(player);

    console.log('selectCard', player, type, index);

    const areasKey = playerNum === 1 ? 'areasP1' : 'areasP2';
    const areas = { ...this.data[areasKey] };
    const card = areas[type][index];

    if (card) {
      if (this.data.selectedIndex === index && this.data.selectedType === type) {
        this.setData({
          selectedIndex: -1,
        })
      } else {
        this.setData({
          selectedIndex: index,
        });
      }
    }
  },


  /**
   * 显示卡牌详情
   */
  showCardDetail(e: any) {
    const { player, type, index } = e.currentTarget.dataset;
    const playerNum = parseInt(player);
    const areasKey = playerNum === 1 ? 'areasP1' : 'areasP2';
    const areas = { ...this.data[areasKey] };
    const card = areas[type][index];
    this.setData({
      detailVisible: true,
      detailCard: this.customData.cardMap[card.id!]
    })
  },




  /**
   * 重置游戏
   */
  resetGame() {
    this.initBattleStatus();
  },

  /**
   * 交换当前活跃玩家
   */
  switchPlayer() {
    this.setData({
      actionType: '' as BattleAreaActionType,
      activePlayer: this.data.activePlayer === 1 ? 2 : 1,
      selectedType: '' as BattleAreaType,
      selectedIndex: -1,
      selectedPlayer: 0
    });
  },

  /**
   * 玩家1换手牌
   */
  changeHandP1() {
    if (this.data.handChangedP1 || this.data.handConfirmedP1) {
      return; // 已经换过手牌或已确认
    }

    const areasP1 = { ...this.data.areasP1 };
    const hand = [...areasP1[BattleAreaType.HAND]];
    const deck = [...areasP1[BattleAreaType.DECK]];

    // 将手牌放回牌库
    for (const card of hand) {
      card.asFold = true;
      deck.push(card);
    }

    // 洗牌
    for (let i = deck.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [deck[i], deck[j]] = [deck[j], deck[i]];
    }

    // 重新抽7张牌
    const newHand = [];
    const handCount = Math.min(7, deck.length);
    for (let i = 0; i < handCount; i++) {
      const card = deck.shift();
      if (card) {
        card.asFold = false;
        newHand.push(card);
      }
    }

    areasP1[BattleAreaType.HAND] = newHand;
    areasP1[BattleAreaType.DECK] = deck;

    this.setData({
      areasP1,
      handChangedP1: true
    });
  },

  /**
   * 玩家2换手牌
   */
  changeHandP2() {
    if (this.data.handChangedP2 || this.data.handConfirmedP2) {
      return; // 已经换过手牌或已确认
    }

    const areasP2 = { ...this.data.areasP2 };
    const hand = [...areasP2[BattleAreaType.HAND]];
    const deck = [...areasP2[BattleAreaType.DECK]];

    // 将手牌放回牌库
    for (const card of hand) {
      card.asFold = true;
      deck.push(card);
    }

    // 洗牌
    for (let i = deck.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [deck[i], deck[j]] = [deck[j], deck[i]];
    }

    // 重新抽7张牌
    const newHand = [];
    const handCount = Math.min(7, deck.length);
    for (let i = 0; i < handCount; i++) {
      const card = deck.shift();
      if (card) {
        card.asFold = false;
        newHand.push(card);
      }
    }

    areasP2[BattleAreaType.HAND] = newHand;
    areasP2[BattleAreaType.DECK] = deck;

    this.setData({
      areasP2,
      handChangedP2: true
    });
  },

  /**
   * 确认玩家1手牌
   */
  confirmHandP1() {
    if (this.data.handConfirmedP1) {
      return; // 已经确认过
    }

    // 从卡组抽7张牌放到生命区
    const areasP1 = { ...this.data.areasP1 };
    const deck = [...areasP1[BattleAreaType.DECK]];
    const life = [...areasP1[BattleAreaType.LIFE]];

    const cardCount = Math.min(7, deck.length);
    for (let i = 0; i < cardCount; i++) {
      const card = deck.shift();
      if (card) {
        card.asFold = true; // 生命区的牌默认背面朝上
        life.push(card);
      }
    }

    areasP1[BattleAreaType.DECK] = deck;
    areasP1[BattleAreaType.LIFE] = life;

    this.setData({
      areasP1,
      handConfirmedP1: true
    });
  },

  /**
   * 确认玩家2手牌
   */
  confirmHandP2() {
    if (this.data.handConfirmedP2) {
      return; // 已经确认过
    }

    // 从卡组抽7张牌放到生命区
    const areasP2 = { ...this.data.areasP2 };
    const deck = [...areasP2[BattleAreaType.DECK]];
    const life = [...areasP2[BattleAreaType.LIFE]];

    const cardCount = Math.min(7, deck.length);
    for (let i = 0; i < cardCount; i++) {
      const card = deck.shift();
      if (card) {
        card.asFold = true; // 生命区的牌默认背面朝上
        life.push(card);
      }
    }

    areasP2[BattleAreaType.DECK] = deck;
    areasP2[BattleAreaType.LIFE] = life;

    this.setData({
      areasP2,
      handConfirmedP2: true
    });
  },

  onPrev() {
    const playerNum = this.data.handConfirmModalVisible ? this.data.selectedPlayer : this.data.activePlayer;
    const areasKey = playerNum === 1 ? 'areasP1' : 'areasP2';
    const cardList = this.data[areasKey][this.data.selectedType];
    let p = this.data.selectedIndex;
    if (p === 0) {
      p = cardList.length - 1;
    } else {
      p--;
    }
    this.setData({
      detailCard: this.customData.cardMap[cardList[p].id!],
      selectedIndex: p
    })
  },

  onNext() {
    const playerNum = this.data.handConfirmModalVisible ? this.data.selectedPlayer : this.data.activePlayer;
    const areasKey = playerNum === 1 ? 'areasP1' : 'areasP2';
    const cardList = this.data[areasKey][this.data.selectedType];
    let p = this.data.selectedIndex;
    if (p === cardList.length - 1) {
      p = 0;
    } else {
      p++;
    }
    this.setData({
      detailCard: this.customData.cardMap[cardList[p].id!],
      selectedIndex: p
    })
  },

  /**
   * 处理区域点击事件
   */
  selectArea(e: any) {
    const { type, player } = e.currentTarget.dataset;
    const playerNum = parseInt(player);
    console.log(type, playerNum);
    let actionLegal = false;
    // 如果当前有等待中的操作，且操作按钮激活时选中的区域和玩家与当前选中区域和玩家相同，则进行操作
    if (this.data.actionType && this.data.selectedPlayer === playerNum && this.data.selectedType !== type) {
      switch (this.data.actionType) {
        case BattleAreaActionType.SWITCH:
          actionLegal = this.doSwitch(this.data.selectedType, type, playerNum);
          break;
        default:
          actionLegal = this.regularMoveAction(this.data.actionType, this.data.selectedType, type, playerNum, this.data.selectedIndex);
          break;
      }
    }
    if (actionLegal) {
      this.setData({
        actionType: '' as BattleAreaActionType,
        selectedType: '' as BattleAreaType,
        selectedIndex: -1,
        selectedPlayer: 0
      });
    } else {
      // 如果当前选中的区域和已选中区域相同且玩家相同，则取消选中
      if (this.data.selectedType === type && this.data.selectedPlayer === playerNum) {
        this.setData({
          actionType: '' as BattleAreaActionType,
          selectedType: '' as BattleAreaType,
          selectedIndex: -1,
          selectedPlayer: 0
        });
      } else {
        // 否则选中该玩家的该区域
        this.setData({
          actionType: '' as BattleAreaActionType,
          selectedType: type,
          selectedIndex: -1,
          selectedPlayer: playerNum
        });
      }

    }

  },

  handPreviewCard(e: any) {
    const { type, index, player } = e.currentTarget.dataset;
    const playerNum = parseInt(player);
    const areasKey = playerNum === 1 ? 'areasP1' : 'areasP2';
    this.setData({
      detailCard: this.customData.cardMap[this.data[areasKey][type][index].id!],
      selectedIndex: index,
      selectedType: type,
      selectedPlayer: playerNum,
      detailVisible: true
    })
  },

  /**
   * 关闭预览区域
   */
  closePreview() {
    this.setData({
      selectedType: '' as BattleAreaType,
      selectedIndex: -1,
      selectedPlayer: 0,
      detailVisible: false
    });
  },

  /**
   * 从卡组上方盖牌到目标区域
   */
  foldCardFromDeckTop() {
    if (this.data.actionType === BattleAreaActionType.FOLD_BOTTOM) {
      this.setData({
        actionType: "" as BattleAreaActionType,
        selectedIndex: -1,
      });
    } else {
      this.setData({
        actionType: BattleAreaActionType.FOLD_BOTTOM,
        selectedIndex: 0,
      });
    }
  },

  /**
   * 查看卡组上方1张牌
   */
  viewTopCardOfDeck() {
    this.regularMoveAction(BattleAreaActionType.MOVE_TOP, BattleAreaType.DECK, BattleAreaType.OP, this.data.selectedPlayer, 0);
  },

  /**
   * 准备动作
   */
  prepareAction(e: any) {
    const { action } = e.currentTarget.dataset;
    this.setData({
      actionType: this.data.actionType === action ? '' as BattleAreaActionType : action
    });
  },

  /**
   * 换位
   */
  doSwitch(fromType: BattleAreaType, toType: BattleAreaType, player: number): boolean {
    if (fromType === toType) {
      return false;
    }
    if (fromType === BattleAreaType.DECK || fromType === BattleAreaType.LIFE || fromType === BattleAreaType.OUTSIDE || fromType === BattleAreaType.REMOVE || fromType === BattleAreaType.HAND || fromType === BattleAreaType.OP || fromType === BattleAreaType.DISPLAY) {
      return false;
    }
    if (toType === BattleAreaType.DECK || toType === BattleAreaType.LIFE || toType === BattleAreaType.OUTSIDE || toType === BattleAreaType.REMOVE || toType === BattleAreaType.HAND || toType === BattleAreaType.OP || toType === BattleAreaType.DISPLAY) {
      return false;
    }
    const areasKey = player === 1 ? 'areasP1' : 'areasP2';
    const areas = { ...this.data[areasKey] };
    const from = [...areas[fromType]];
    const to = [...areas[toType]];
    areas[fromType] = to;
    areas[toType] = from;
    this.setData({
      [areasKey]: areas
    });
    return true;
  },

  /**
   * 切换卡牌状态（激活/休息）
   */
  statusSwitch() {
    const { selectedType, selectedPlayer } = this.data;

    if (!selectedType || selectedPlayer === 0) {
      return;
    }

    const statusKey = selectedPlayer === 1 ? 'activeStatusP1' : 'activeStatusP2';
    const status = { ...this.data[statusKey] };
    status[selectedType] = !status[selectedType];

    this.setData({
      [statusKey]: status
    });
  },

  // 将卡片从一个区域移动到另一个区域。当cardIndex为-1时，表示移动所有卡片。
  regularMoveAction(actionType: BattleAreaActionType, fromType: BattleAreaType, toType: BattleAreaType, player: number, cardIndex: number): boolean {
    const areasKey = player === 1 ? 'areasP1' : 'areasP2';
    const areas = { ...this.data[areasKey] };
    const fromCards = [...areas[fromType]];
    const toCards = [...areas[toType]];

    // 检查源区域是否有卡牌
    if (fromCards.length === 0) {
      wx.showToast({ title: '源区域没有卡牌', icon: 'none' });
      return false;
    }

    // 获取要移动的卡牌
    if (cardIndex >= 0 && cardIndex < fromCards.length) {
      // 移动指定索引的卡牌
      let card = fromCards.splice(cardIndex, 1)[0];
      // 根据动作类型处理卡牌状态
      switch (actionType) {
        case BattleAreaActionType.FOLD_TOP:
          card.asFold = true;
          toCards.unshift(card); // 盖牌到顶部
          break;
        case BattleAreaActionType.FOLD_BOTTOM:
          card.asFold = true;
          toCards.push(card); // 盖牌到底部
          break;
        case BattleAreaActionType.MOVE_TOP:
          card.asFold = false;
          toCards.unshift(card); // 明牌到顶部
          break;
        case BattleAreaActionType.MOVE_BOTTOM:
          card.asFold = false;
          toCards.push(card); // 明牌到底部
          break;
      }

      // 更新区域数据
      areas[fromType] = fromCards;
      areas[toType] = toCards;

      this.setData({
        [areasKey]: areas,
        actionType: '' as BattleAreaActionType,
        selectedIndex: -1,
      });

    } else {
      if (actionType === BattleAreaActionType.FOLD_TOP || actionType === BattleAreaActionType.FOLD_BOTTOM) {
        for (const card of fromCards) {
          card.asFold = true;
        }

      } else {
        for (const card of fromCards) {
          card.asFold = false;
        }
      }

      areas[fromType] = [];
      if (actionType === BattleAreaActionType.FOLD_TOP || actionType === BattleAreaActionType.MOVE_TOP) {
        areas[toType] = [...fromCards, ...toCards];
      } else {
        areas[toType] = [...toCards, ...fromCards];
      }

      this.setData({
        [areasKey]: areas,
        actionType: '' as BattleAreaActionType,
        selectedIndex: -1,
      });
    }

    return true;
  },

  flipCard() {
    const { selectedPlayer } = this.data;
    const areasKey = selectedPlayer === 1 ? 'areasP1' : 'areasP2';
    const areas = { ...this.data[areasKey] };
    areas[this.data.selectedType][this.data.selectedIndex].asFold = !areas[this.data.selectedType][this.data.selectedIndex].asFold;
    this.setData({
      [areasKey]: areas
    });
  }

})